<template>
  <div class="app-main-container">
    <div class="warnningTip">
      <i class="el-icon-warning-outline" />{{
        translate("discouponAppUseDesc")
      }}
    </div>
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @changeForm="changeForm"
      @clear="clear"
    />
    <div v-if="meta.indexOf('CouponAdd') > -1" class="doumee-table-buttons">
      <el-button type="primary" @click="toVipCardAdd">{{
        translate("add")
      }}</el-button>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column
        align="center"
        :label="translate('disCouponName')"
        width="220"
        show-overflow-tooltip
      >
        <template v-slot="scope">
          <span class="primaryColor pointer" @click="detailClick(scope.row)">{{
            scope.row.couponsName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="translate('lx')" min-width="80">
        <template slot-scope="scope">
          <span>{{
            scope.row.couponsType == "0"
              ? translate("disCouponN")
              : translate("voucher")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="translate('giveChannel')"
        min-width="80"
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.couponsChannel == "1"
              ? translate("userClaim")
              : scope.row.couponsChannel == "3"
                ? translate("dirMarketing")
                : translate("integralEx")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="translate('couponRules')"
        prop="disRule"
        show-overflow-tooltip
        min-width="200"
      />
      <el-table-column
        align="center"
        :label="translate('allAmount')"
        prop="circulation"
        show-overflow-tooltip
        min-width="80"
      />
      <el-table-column
        align="center"
        :label="translate('received')"
        prop="getNum"
        show-overflow-tooltip
        min-width="80"
      />
      <el-table-column
        align="center"
        :label="translate('sy')"
        prop="remaining"
        show-overflow-tooltip
        min-width="80"
      />
      <el-table-column
        align="center"
        :label="translate('limitTime')"
        min-width="220"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <div v-if="scope.row.receiveStartTime">
            {{ translate("rise") }}：{{ scope.row.receiveStartTime }}
          </div>
          <div v-if="scope.row.receiveEndTime">
            {{ translate("stop") }}：{{ scope.row.receiveEndTime }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="translate('applyVenue')"
        prop="stadiumInfo"
        show-overflow-tooltip
        min-width="200"
      />
      <el-table-column
        align="center"
        :label="translate('status')"
        min-width="80"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.couponsStatus"
            active-value="1"
            inactive-value="0"
            :disabled="meta.indexOf('CouponEnable') == -1"
            @change="editStatus(scope.row.couponsId, scope.row.couponsStatus)"
          />
        </template>
      </el-table-column>
      <el-table-column
        :label="translate('handle')"
        :width="$i18n.locale === 'ZH'? 100 : 160"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div
            v-if="
              scope.row.getNum < 1 &&
                scope.row.couponsStatus == '0' &&
                meta.indexOf('CouponEdit') > -1
            "
            class="flex-cc"
          >
            <el-button
              v-preventReClick
              type="text"
              @click="toEdit(scope.row.couponsId)"
            >{{ translate("edit") }}</el-button>
            <el-button
              v-if="meta.indexOf('CouponDel') > -1"
              v-preventReClick
              type="text"
              style="color: red"
              @click="toDelete(scope.row.couponsId)"
            >{{ translate("del") }}</el-button>
          </div>
          <div
            v-if="
              scope.row.couponsStatus == '1' && meta.indexOf('CouponAdd') > -1
            "
            class="flex-cc"
          >
            <el-button
              v-preventReClick
              type="text"
              @click="toEdit(scope.row.couponsId, 'copy')"
            >{{ translate("copy") }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="totalCount"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />
    <CouponAdd
      v-if="isShowCouponAdd"
      ref="CouponAddRef"
      @success="CouponAddSuccess"
      @close="isShowCouponAdd = false"
    />
    <CouponDetail ref="CouponDetailRef" :meta="meta" />
  </div>
</template>

<script>
import {
  couponsList,
  venueList,
  projectList,
  orderTypeList,
  couponsEnable,
  couponsDel
} from '@/api'
import { parseTime } from '@/utils/index'
import Pagination from '@/components/paginations'
import { queryFormConfig } from './config'
import CouponAdd from '../couponAdd/index.vue'
import CouponDetail from './detail.vue'
export default {
  name: 'Coupon',
  components: {
    Pagination,
    CouponAdd,
    CouponDetail
  },
  data() {
    return {
      isShowCouponAdd: false,
      visible: false,
      queryFormConfig,
      totalCount: 0,
      list: [],
      meta: [],
      listLoading: true,
      venueList: [],
      orderType: [],
      pagination: {
        page: 1,
        rows: 10
      },
      suitableVenue: [],
      filters: {}
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getVenueList()
    // this.getOrderTypeList()
    this.getList(1)
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    CouponAddSuccess() {
      this.isShowCouponAdd = false
      this.getList()
    },
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    getValidityTime(value) {
      return value.validityType === '0'
        ? value.validityStartTime + '-' + value.validityEndTime
        : value.validityDays + this.translate('days')
    },
    toVipCardAdd() {
      this.isShowCouponAdd = true
      this.$nextTick(() => {
        this.$refs.CouponAddRef.isShowDrawer = true
      })
    },
    // 编辑
    toEdit(id, type) {
      this.isShowCouponAdd = true
      this.$nextTick(() => {
        this.$refs.CouponAddRef.isShowDrawer = true
        if (type && type === 'copy') {
          this.$refs.CouponAddRef.copName = this.translate('disCouponAdd')
        } else {
          this.$refs.CouponAddRef.copName = this.translate('disCouponEdit')
          this.$refs.CouponAddRef.id = id
        }
        this.$refs.CouponAddRef.getCouponDetailInfo(id)
      })
      // this.$router.push({ name: 'CouponAdd', query: { id: id }})
    },
    detailClick(row) {
      const { couponsId } = row
      // this.$refs.CouponDetailRef.detail = row
      this.$refs.CouponDetailRef.getCouponDetailInfo(couponsId, row)
      this.$refs.CouponDetailRef.isShowDrawer = true
    },
    // 获取场馆列表
    getVenueList() {
      venueList({
        param: {}
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          // this.venueList = res.recordList
          const arr = res.recordList
          arr.forEach(e => {
            e.label = e.name
            e.value = e.id
          })
          this.queryFormConfig.formItems[4].options = arr
        })
        .catch(() => { })
    },
    // 获取项目列表
    getProjectList() {
      if (!this.filters.stadiumId) return
      projectList({
        param: { venueId: this.filters.stadiumId }
      }).then((res) => {
        if (res.errorCode !== '000000') return
        const arr = res.recordList
        const obj = { ... this.queryFormConfig }
        arr.forEach(e => {
          e.label = e.projectName
          e.value = e.id
        })
        obj.formItems[5].options = arr
        this.queryFormConfig = obj
      })
    },
    // 获取订单类型列表
    getOrderTypeList() {
      orderTypeList({ param: { type: 'ORDER_TYPE_COUPONS' }}).then((res) => {
        if (res.errorCode !== '000000') return
        const arr = res.recordList
        arr.forEach(e => {
          e.label = e.name
          e.value = e.id
        })
        this.queryFormConfig.formItems[6].options = arr
      })
    },
    // 获取优惠券列表
    getList(page) {
      this.listLoading = true
      const { filters, pagination } = this
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      if (pagination.page === 1) {
        pagination.firstQueryTime = parseTime(new Date())
      }
      couponsList({
        pagination,
        userId: sessionStorage.getItem('userId'),
        param: { ...filters }
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            this.list = res.recordList
            this.totalCount = res.totalCount
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 启用或禁用
    editStatus(couponsId, status) {
      couponsEnable({
        param: {
          couponsId: couponsId,
          couponsStatus: status
        },
        userId: sessionStorage.getItem('userId')
      })
        .then((res) => {
          if (res.errorCode === '000000') {
            this.$message.success(status === 1 || status === '1' ? this.translate('qyScs') : this.translate('jyScs'))
            this.getList()
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 删除
    toDelete(couponsId) {
      const that = this
      this.$confirm(this.translate('disCouponDelPlace'), this.translate('ts'), {
        confirmButtonText: this.translate('qd'),
        cancelButtonText: this.translate('cancel'),
        type: 'warning'
      })
        .then((res) => {
          couponsDel({ param: { couponsId }, userId: sessionStorage.getItem('userId') }).then((res) => {
            if (res.errorCode !== '000000') return
            that.$message.success(this.translate('delScs'))
            that.getList()
          })
        })
        .catch(() => {
          // this.$message.info(this.translate('canceledDel'))
        })
    },
    venuechange() {
      this.$set(this.filters, 'itemsId', '')
      this.suitableProject = []
      this.getProjectList()
    },
    changeForm(e) {
      if (e === 'stadiumId') {
        this.venuechange()
      }
    },
    // 清空
    clear() {
      this.filters = {}
      this.getList(1)
    }
  }
}
</script>
